package com.loop.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用一个buffer完成文件的拷贝
 *
 * @author zhangxiaolu
 * @since 2023-09-03 21:01
 */
public class NIOFileChannel03 {

    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel channel01 = fileInputStream.getChannel();
        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel channel02 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true) {
            // 这里有个重要的操作
            byteBuffer.clear(); // 清空buffer
            int read = channel01.read(byteBuffer);
            if (read == -1) {// 读取完毕
                break;
            }
            byteBuffer.flip(); // 切换到读取模式
            channel02.write(byteBuffer);
        }
        // 关闭流
        channel01.close();
        channel02.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}
